/**
 * Created by liuqingxia on 2016/3/22.
 */

var params = {
	pageSize : 10
};

var currentAppId;

/* 分表配置列表 */
var appdatasourceTable;// 无参数
var diamondTable;// diamond查询
/**
 * main入口
 */
$(document).ready(function() {

	LTS.colFormatter.optFormat = function(v, row) {
		return generateOptNewRule(row);
	}

	LTS.colFormatter.diamondRule = function(v, row) {
		return generateOptDiamondResult(row);
	}

	LTS.colFormatter.groupNameRule = function(v, row) {
		return generateOptNewRule(row);
	}
	appdatasourceTable = $("#tddl-app-datasource-table-container").ltsTable({
		url : getUrlBySuffix("/tddl/atom/findAppDataSourceByPage"),
		templateId : 'tddl-app-datasource-table-template'
	});

	appdatasourceTable.post(params, 1);

	diamondTable = $("#tddl-diamond-table-container").ltsTable({
		url : getUrlBySuffix("/tddl/atom/getDiamondInfo"),
		templateId : 'tddl-diamond-table-template'
	});

	searchBtnEvent();
	clickDBRuleBtn();
	clickDeleteBtn();
	clickDBSetBtn();
	/* app添加页 */
	clickAppInsertBtn();
	submitAppConfig();
	isDisabled();
	clickReloadSearchBtn();
	clickValidateRuleBtn();
	getDiamondInfo();
	diamondModalCommit();
	batchDeleteInvalidData();
});

/**
 * 数据源状态
 * 
 * @param row
 * @returns {*}
 */
function sourceState(row) {
	var status = row['sourceState'];
	if (isNull(status)) {
		return "";
	}

	if (status == "可用") {
		return "<span style='color: green'>可用</span>";
	} else if (status == "不可用") {
		return "<span style='color: red'>不可用</span>";
	}
}

/**
 * 点击新建分表配置按钮
 */
function clickAppInsertBtn() {
	$(document).on("click", "#insertBtn", function() {
		window.location.href = getUrlBySuffix("/tddl/grop/toSaveGroupPage");
	});
}
/**
 * 验证规则
 */
function clickValidateRuleBtn() {
	$(document).on("click", "#validateRuleBtn", function() {
		$("#validateRuleGenerator-modal").modal("show");
	});
}

/**
 * 生成按钮
 */
function generateOptNewRule(jsonObj) {
	var optButtons = '<a href="javascript:;" class="DBSearch-btn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-edit"></i>&nbsp;&nbsp;' + '修改'
			+ '</span>' + '</a>&nbsp;'
			+'<a href="javascript:;" class="delete-btn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-delete"></i>&nbsp;&nbsp;' + '删除'
			+ '</span>' + '</a>&nbsp;';

	return optButtons;
}

/**
 * 生成按钮
 */
function generateOptDiamondResult(jsonObj) {
	var optButtons = '<a href="javascript:;" class="showDiamondContent-btn">'
			+ '<span class="label label-success" style="font-size: 14px">'
			+ '<i class="fa fa-search"></i>&nbsp;&nbsp;' + '查看信息' + '</span>'
			+ '</a>&nbsp;';

	return optButtons;
}

/**
 * 根据id获取AppDataSource
 * 
 * @param id
 * @returns {*}
 */
function getAppDataSource(id) {
	var dataSource;
	$.postHttpSync({
		id : id
	}, getUrlBySuffix("/tddl/appDataSource/findById"), function(json) {
		if (json && json.success) {
			var list = json['list'];
			dataSource = list[0];
		}
	})
	return dataSource;
}

function getDiamondInfo() {
	$(document).on(
			"click",
			".showDiamondContent-btn",
			function() {
				var configId = getCurrentId($(this));
				var url = getUrlBySuffix("/tddl/atom/showDiamondInfo");
				var param = {
					configInfoId : Number(configId)
				}
				$.post(url, param, function(json) {
					if (json && json.success) {
						// swal("成功","加载成功","success");
						var obj = json.list[0];
						$("#updataDiamondContent").find("input[name=Id]").val(
								obj.id);
						$("#updataDiamondContent").find("input[name=dataId]")
								.val(obj.dataId);
						$("#updataDiamondContent").find("#content").html(
								obj.content);
						$("#tddl-diamond-modal").modal("show");
					} else {
						swal("提示", "查询失败，请联系管理员", "error");
					}
				});
			})
}

function diamondModalCommit() {
	$(document).on(
			"click",
			"#commitDiamondBtn",
			function() {
				var param = getDiamondInfoFromWeb();
				var url = getUrlBySuffix("/tddl/atom/updateDiamondLists");
				$.post(url, param, function(json) {
					if (json && json.success) {
						$("#tddl-diamond-info-modal").modal("hide");
						swal("成功", "加载成功", "success");
						appdatasourceTable.post(params, pageNum);
					} else {
						swal("提示", "查询失败，请联系管理员", "error");
					}
				});

			})
}

function getDiamondInfoFromWeb(){
	var configInfolist='[';
	var appDatasource='';
	var formlist=$("#tddl-diamond-info-modal").find(".commitdata");
	for(var i=0;i<formlist.length;i++){
		var formObj=formlist[i];
		if($(formObj).attr("id")=="appDatasourcePartEdit"){
			var userName=$(formObj).find("input[name=appDatasourceuserName]").val();
			var jdbcUrl=$(formObj).find("input[name=appDatasourceJdbcUrl]").val();
			var sourceType=$(formObj).find("input[name=appDatasourceSourceType]").val();
			var appId=$(formObj).find("input[name=appDatasourceAppId]").val();
			var dbName=$(formObj).find("input[name=appDatasourceDbName]").val();
			var id=$(formObj).find("input[name=appDatasourceId]").val();
			//var tempInfo='{"userName":"'+userName+'","jdbcUrl":"'+jdbcUrl+'","sourceType":"'+sourceType+'","dbName":"'+dbName+'","appId":"'+appId+'","id":"'+id+'"}';
			var tempInfo='{"appDatasource":"'+$(formObj).find(".content").val()+'"}';
			appDatasource +=tempInfo;
		}else{
			var tempDataId=$(formObj).find("input[name=dataId]").val();
			var tempId=$(formObj).find("input[name=Id]").val();
			var tempContent=$(formObj).find(".content").val();
			var _temp='{"dataId":"'+tempDataId+'","id":"'+tempId+'","content":"'+tempContent+'"},';
			configInfolist +=_temp;
		}
	}
	appDatasource +="";
	configInfolist = configInfolist.substring(0, configInfolist.lastIndexOf(","));
	configInfolist += "]";
	var paramsData={};
	paramsData.configInfolist=configInfolist;
	paramsData.appDatasource=appDatasource;
	
	return paramsData;
	
}
function clickDeleteBtn(){
	$(document).on("click",".delete-btn",function(){
		var currentId = getCurrentId($(this));
		var url = getUrlBySuffix("/tddl/atom/deleteInvalidData");
		$.post(url,{"appDsId":currentId},function(map){
			if(map.success){
				swal("成功","删除成功",'success');
			}else{
				if(!map.success){
					swal("失败","删除失败",'error');
				}
			}
		})
	})
}
/**
 * 点击修改diamond按钮
 * */
function clickDBRuleBtn() {
	$(document).on("click", ".DBSearch-btn", function() {
		var appDataSourceId = getCurrentId($(this));
		currentAppDataSourceId = appDataSourceId;
		$("#datasourceId").val(appDataSourceId);
		var params = {
			appdatasourceid : Number(currentAppDataSourceId)
		}
		var url = getUrlBySuffix("/tddl/atom/getDiamondList");
		getDiamondInfoList(params,url);
	});
}
function getDiamondInfoList(params,url){
	$.post(url,params,function(json){
		if(json && json.success){
			var map=json.list[0];
			getDiamondInfoToModal(map);
			$("#tddl-diamond-info-modal").modal("show");
		}else{
			swal("提示", "查询失败，请联系管理员", "error");
		}
	})
}

function getDiamondInfoToModal(map){
	$("#defaultGlobal,#remoteGlobal,#defaultApp,#remoteApp,#defaultPasswd,#remotePasswd").empty();
	var app = map.appBOPart;
	var appDatasource = map.appDatasourcePart;
	var globalDiamond = map.globalPart;
	var appDiamond = map.appPart;
	var passwdDiamod = map.pwdPart;
	var tag = map.tag;
	$("#diamondAppName").empty().append(app.appName);
	var database = appDatasource.sourceType+'@'+appDatasource.jdbcUrl+'/'+appDatasource.dbName;
	$("#diamondDatabase").empty().append(database);
	$("#diamondDbuser").empty().append(appDatasource.userName);
	$("#dbKey").empty().val(appDatasource.dbName);
	
	if(tag == 1){
		$("#globalDataId").empty().append('com.taobao.tddl.atom.global.'+globalDiamond.groupRuleName);
		$("#appDataId").empty().append('com.taobao.tddl.atom.app.'+app.appName+'.'+globalDiamond.groupRuleName);
	}else if(tag == 0){
		$("#globalDataId").empty().append('com.taobao.tddl.atom.global.'+appDatasource.dbName);
		$("#appDataId").empty().append('com.taobao.tddl.atom.app.'+app.appName+'.'+appDatasource.dbName);
	}
	
	$("#defaultGlobal,#remoteGlobal").empty().append(globalDiamond.content);
	$("#defaultApp,#remoteApp").empty().append(appDiamond.content);
	$("#passwdDataId").empty().append('com.taobao.tddl.atom.passwd.'+appDatasource.dbName+'.'+appDatasource.sourceType+'.'+appDatasource.userName);
	$("#defaultPasswd,#remotePasswd").empty().append(passwdDiamod.content);
}

/**
 * 点击‘重新加载’按钮
 */
function clickReloadSearchBtn() {
	$(document).on("click", ".reloadSearch-btn", function() {
		var configId = getCurrentId($(this));

		var dataId = getCurrentAppName($(this));
		var url = getRoot() + "/tddl/grop/reloadMSInfo";
		$("#appLoadingGenerator").modal("show");
		$.post(url, {
			"configId" : configId
		}, function(json) {
			if (json && json.success) {
				$("#appLoadingGenerator").modal("hide");

				swal("成功", "加载成功", "success");
				var param = {
					type : "group_name",
					keyWord : $("#keyword").val()
				}
				groupNameTable.post(param, 1);
				$(".result").hide();
				$("#tddlGroupName").show();
			} else {
				swal("提示", "查询失败，请联系管理员", "error");
			}

		});
	});
}

/**
 * 点击设置
 */
function clickDBSetBtn() {
	$(document).on("click", ".set-btn", function() {
		var appId = getCurrentId($(this));
		currentAppId = appId;
		var url = getRoot() + "/tddl/app/findAppConfigById";
		$.post(url, {
			"appId" : appId
		}, function(data) {
			if (data != null) {
				$("#delayTime").removeAttr("disabled");
				$("#isSwitchAuto").val(data.isAutoSwitch);
				$("#delayTime").val(data.switchDelayTime);
				if (data.isAutoSwitch == 0) {
					$("#delayTime").val("");
					$("#delayTime").attr("disabled", "false");
				}
			}
			if (data == null || data == '' || data == 'undefined') {
				$("#isSwitchAuto").val(0);
				$("#delayTime").val("");
				$("#delayTime").attr("disabled", "false");
			}
		});
		$("#appConfigGenerator-modal").modal("show");
	});
}

/**
 * 点击设置 确定按钮
 */
function submitAppConfig() {
	$("#commit-appcontrim-btn").click(function() {
		var appsId = currentAppId;
		var isSwitch = $("#isSwitchAuto").val();
		var delayTime = $("#delayTime").val();
		var url = getRoot() + "/tddl/app/saveAppConfig";
		$.post(url, {
			"appId" : appsId,
			"isSwitch" : isSwitch,
			"delayTime" : delayTime
		}, function(data) {
			if (data == 'success') {
				$("#appConfigGenerator-modal").modal("hide");
				swal("success", "修改成功", "success");
			} else {
				swal("error", "修改失败", "error");
			}
		});
	});
}
function isDisabled() {
	$("#selectID").click(function() {
		var isSwitch = $("#isSwitchAuto").val();
		if (isSwitch == 1) {
			$("#delayTime").removeAttr("disabled");
		}
		if (isSwitch == 0) {
			$("#delayTime").val("");
			$("#delayTime").attr("disabled", "false");
		}
	});
}
/**
 * "分表规则"/"分组规则"标题切换
 * 
 * @param title
 */
function changeRuleTitleSpan(title) {
	var titleSpan = $("#ruleTitle-span");
	titleSpan.empty();
	titleSpan.append($.trim(title));
}

/**
 * 展示分库规则表格
 * 
 * @param containerId
 * @param appId
 */
function showAppDataSourceTable(containerId, appId) {
	var groupRuleVOs = getGroupRuleVOByGroupId(groupId);
	var splitGroupRuleVOs = getSplitGroupRuleVOs(groupRuleVOs);
	var container = $("#" + containerId);
	container.empty();
	container.append(generateGroupRuleVOTable(splitGroupRuleVOs));
}

function getGroupRuleVOByGroupId(groupId) {
	var groupRuleVOs = [];
	$.postHttpSync({
		groupId : Number(groupId)
	}, getUrlBySuffix("/tddl/grop/findGroupRuleByGroupId"), function(json) {
		if (json && json.success) {
			groupRuleVOs = json['list'];
		}
	})
	return groupRuleVOs;
}
/**
 * 点击搜索事件
 * 
 */

function searchBtnEvent() {
	$(document).on("click", ".btn-search", function() {
		var type = $(this).attr("searchtype");
		var keyWord = $("#keyword").val();
		var param = {
			keyWord : keyWord
		}
		appdatasourceTable.post(param, 1);

	})
}

function batchDeleteInvalidData(){
	$(document).on("click","#batchDeleteBtn",function(){
		var url = getRoot() + '/tddl/atom/batchDeleteInvalidData';
		$.post(url,{"a":1},function(map){
			if(map.success){
				swal('成功',map.msg,'success');
			}else{
				if(!map.success){
					swal('error','失败','error');
				}
			}
		})
	})
}
